package com.vinku.agent.transformer;

import javassist.*;

import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.time.Instant;

/**
 * @Author Vinku
 * @Date 2022/10/21
 * @Description
 */
public class StopWatchTransformer implements ClassFileTransformer {

    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        if (!className.startsWith("com/vinku/app")) {
            return classfileBuffer;
        }
        try {
            ClassPool cp = ClassPool.getDefault();
            CtClass ctClass = cp.getCtClass(className.replace("/", "."));
            for (CtMethod method : ctClass.getDeclaredMethods()) {
                method.addLocalVariable("beginTime", CtClass.longType);
                method.insertBefore("beginTime = System.currentTimeMillis();");
//                method.insertBefore("System.out.println(\"开始计时\");");
                method.insertAfter("System.out.print(\""+ method.getName() +"()Javassist统计耗时:\");");
                method.insertAfter("System.out.println(System.currentTimeMillis() - beginTime + \"ms\");");
            }
            return ctClass.toBytecode();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return classfileBuffer;
    }

}
